import { createRouter, createWebHistory } from "vue-router";
import Home from "@/views/Home.vue";
import store from "@/store";
import dayjs from "dayjs";

const routes = [
	{
		path: "/",
		name: "home",
		component: Home,
		meta: {
			title: "零碎、记忆",
		},
		strict: true,
	},
	{
		path: "/search",
		name: "search",
		component: () => import("../views/Search.vue"),
		meta: {
			title: "零碎、记忆 - 搜索结果",
		},
	},
	{
		path: "/write/:id*",
		name: "write",
		component: () => import("../views/Write.vue"),

		meta: {
			title: "零碎、记忆 - 写文章",
			isAuth: true,
		},
	},
	{
		path: "/article/:id",
		name: "article",
		component: () => import("../views/Article.vue"),
		meta: {
			title: "零碎、记忆",
		},
	},
	{
		path: "/tools",
		name: "tools",
		component: () => import("../views/Tools.vue"),
		meta: {
			title: "零碎、记忆 - 工具下载",
		},
	},
	{
		path: "/nav/:id",
		name: "nav",
		component: () => import("../views/Nav.vue"),
		meta: {
			title: "零碎、记忆 - 文章分类",
		},
	},
	{
		path: "/type",
		name: "type",
		component: () => import("../views/Type.vue"),
		meta: {
			title: "零碎、记忆 - 文章类型管理",
		},
	},
	{
		path: "/personal",
		name: "personal",
		component: () => import("../views/PersonalCenter.vue"),
		meta: {
			title: "零碎、记忆 - 个人中心",
		},
	},
	{
		path: "/login",
		name: "login",
		component: () => import("../views/Login.vue"),
		meta: {
			title: "零碎、记忆 - 用户登录",
		},
	},
	{
		path: "/404",
		name: "404",
		component: () => import("../views/PageNotFound.vue"),
		meta: {
			title: "零碎、记忆 - 页面未找到",
		},
	},
	{
		// 新改版的，需要使用以下表达式匹配404
		path: "/:catchAll(.*)",
		redirect: "/404",
	},
];

const router = createRouter({
	history: createWebHistory(process.env.BASE_URL),
	routes,
});

router.beforeEach((to, from, next) => {
	// 动态修改标题
	if (to.meta && to.meta.title) {
		document.title = to.meta.title;
	}
	// 判断页面是否需要登录
	if (
		to.meta.isAuth &&
		(!store.getters.token ||
			dayjs(store.state.userinfo.expiresTime).isBefore(new Date()))
	) {
		next("/login");
	} else {
		// 判断写文章改动后是否跳转
		if (from.path.indexOf("/write") > -1 && !store.state.saveStatus) {
			// 提示是否离开
			if (confirm("网站不会保存您的更改，是否离开？")) {
				next();
			}
		} else {
			next();
		}
	}
});

export default router;
